﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace CustomNetworking
{
    class SimpleServer
    {
        static void Main(string[] args)
        {
            new SimpleServer(4000);
            Console.Read();
        }

        private TcpListener server;
        StringSocket socket;

        public SimpleServer(int port)
        {
            server = new TcpListener(IPAddress.Any, port);
            server.Start();
            server.BeginAcceptSocket(ConnectionRequested, null);
        }

        public void ConnectionRequested(IAsyncResult result)
        {
            Socket s = server.EndAcceptSocket(result);
            socket = new StringSocket(s, new UTF8Encoding());
            socket.BeginReceive(MessageReceived, null);
            Console.WriteLine("Connection accepted.");
        }

        private void MessageReceived(String s, Exception o, object payload)
        {
            Console.WriteLine("Message received: {0}\n{1}\n", s.Length, s);
            socket.BeginReceive(MessageReceived, null);
        }
    }
}
